package ch.usi.da.udp;

import sun.security.krb5.internal.UDPClient;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Sergey Karakovskiy, sergey at idsia dot ch
 * Date: Nov 25, 2009
 * Time: 5:34:13 PM
 * Package: ch.usi.da.udp
 */
public class CustomUDPServer
{
    public void startServer(int portNumber)
    {
        byte [] buffer = new byte[1024];
        String myMessage ;

        try
        {
            // Create a Datagram Socket
            DatagramSocket socket = new DatagramSocket(portNumber);
            System.out.println("Server: Datagram Socket has been created on port " + portNumber + "...");

            // Create an empty Datagram Packet

            while (true)
            {
                // receive request from client and get client info
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length );
                socket.receive(packet);
                InetAddress client = packet.getAddress();
                int client_port = packet.getPort();
                System.out.println("Server: Received <"+new String(buffer)+"> from "+client);

                // send some data to the client
                myMessage = "Here is your stuff" + new Date();
                byte[] bufferToSend = myMessage.getBytes("US-ASCII");
                packet = new DatagramPacket(bufferToSend, bufferToSend.length, client, client_port);

//                packet.setData(buffer);
//                packet.setLength(buffer.length);
//                packet.setAddress(client);
//                packet.setPort(client_port);
                socket.send(packet);
            }
        }
        catch(UnknownHostException e){ System.out.println(e); }
        catch(IOException e){ System.out.println(e); }
    }
}